/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/21
 * Time: 14:41
 */
package api

import (
	"blogApi/controllers"
	"blogApi/models"
	"github.com/astaxie/beego/orm"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type UserController struct {
	controllers.BaseController
}

func (self *UserController) Prepare() {

}

//用户登录
func (self *UserController) Login() {
	if self.Ctx.Input.IsPost() {
		account := self.Ctx.Input.Param("account")
		password := self.Ctx.Input.Param("password")

		o := orm.NewOrm()
		admin := new(models.Admin)
		qs := o.QueryTable(admin) // 获取 QuerySeter 对象
		cond := orm.NewCondition()
		cond1 := cond.And("account", account).Or("tel", account).Or("email", account)
		cond2 := cond.And("status", 1).And("deleted_atnull", true)
		conds := cond.AndCond(cond1).AndCond(cond2)
		qs = qs.SetCond(conds)
		err := qs.One(&admin)
		if err == orm.ErrMultiRows { // 多条的时候报错
			self.ResJson(1, "获取失败", "返回的多行不是一个", nil)
		}
		if err == orm.ErrNoRows { // 没有找到记录
			self.ResJson(1, "获取失败", "账号错误", nil)
		}
		//验证密码
		password = "123456"
		if password != "123456" {
			self.ResJson(1, "获取失败", "密码错误", nil)
		}
		// 带权限创建令牌
		claims := make(jwt.MapClaims)
		claims["account"] = admin.Account
		claims["username"] = admin.Username
		claims["tel"] = admin.Tel
		claims["email"] = admin.Email
		claims["exp"] = time.Now().Add(time.Hour * 2).Unix() //2小时有效期，过期需要重新登录获取token
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
		// 使用自定义字符串加密 and get the complete encoded token as a string
		//tokenString, err := token.SignedString([]byte("mykey"))
		//if err != nil {
		//	return
		//}
		jsonData := make(map[string]interface{}, 4)
		jsonData["token"] = token
		jsonData["id"] = admin.Id
		jsonData["account"] = admin.Account
		jsonData["username"] = admin.Username
		jsonData["tel"] = admin.Tel
		jsonData["email"] = admin.Email
		self.ResJson(0, "获取成功", jsonData, nil)
	} else {
		self.ResJson(1, "请求失败", "请求方式错误", nil)
	}
}
